package com.hhf.feiojcommonservice.interceptor;

import com.hhf.feiojcommonservice.common.ErrorCode;
import com.hhf.feiojcommonservice.exception.BusinessException;
import com.hhf.feiojcommonservice.utils.UserIdContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求响应日志 AOP
 *
 * @author hhf
 * @data 2024/9/26
 **/
@Aspect
@Component
@Slf4j
public class UserIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头获取userId
        String userId = request.getHeader("userId");

        //判断是否为空,保存至ThreadLocal
        if (StringUtils.isNotBlank(userId)){
            UserIdContext.setUserId(Long.parseLong(userId));
        }

        //放行
        return true;

    }

    /**
     * 每次结束完请求头,释放threadlocal中的数据,防止出现线程安全问题
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserIdContext.removeUserId();
    }
}

